package com.zahb.qadx.ui.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.base.BaseFragmentExt;
import com.zahb.qadx.databinding.ItemFunctionBinding;
import com.zahb.qadx.model.Curriculum;
import com.zahb.qadx.model.DataLogin;
import com.zahb.qadx.model.Function;
import com.zahb.qadx.model.TaskListBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.AnswerExercisesActivity;
import com.zahb.qadx.ui.activity.CurriculumDetailsActivity;
import com.zahb.qadx.ui.activity.ExaminationListActivity;
import com.zahb.qadx.ui.activity.MyCourseActivity;
import com.zahb.qadx.ui.activity.MyTrainActivity;
import com.zahb.qadx.ui.activity.TaskListActivity;
import com.zahb.qadx.ui.activity.topic.TheTestActivity;
import com.zahb.qadx.ui.view.adapter.BaseViewBindingHolder;
import com.zahb.qadx.util.ClickCheck;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by huwei.
 * Data 2020-09-29.
 * Time 09:28.
 */
public class TaskFragment extends BaseFragmentExt implements View.OnClickListener, OnItemClickListener {

    private RecyclerView gridView;

    private TaskAdapter mTaskAdapter;

    private boolean mHasClickToNewPage = false;// 记录点击跳转新页面

    private LinearLayoutCompat linearLayoutCompat;

    private RecyclerView recyclerView;

    private TextView tVlearnTime;

    private TextView tVcourseCount;

    private TextView tVtrainingCount;

    private TextView tVexamCount;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LiveEventBus.get(Constant.KEY_ROOT_ORG_ID_CHANGED, Integer.class)
                .observe(this, integer -> {
                    BaseApplication.getContext().getDataLogin().setCurrentOrg(integer);
                    getTaskData();
                    getStudyData();
                });
        LiveEventBus.get(Constant.KEY_USER_LOGIN_STATUS_CHANGED, DataLogin.class)
                .observe(this, dataLogin -> {
                    BaseApplication.getContext().setDataLogin(dataLogin);
                    getTaskData();
                    getStudyData();
                });
    }



    @Override
    public void onResume() {
        super.onResume();
        if (mHasClickToNewPage) {
            mHasClickToNewPage = false;
            getTaskData();
            getStudyData();
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_all) {//我的任务
            TaskListActivity.actionStart(getContext());
        }
    }

    @Override
    public void onStart() {
        tryToSwitch();//试题切换
        super.onStart();
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_task;
    }

    @Override
    protected void initViews(View rootView) {
        gridView = rootView.findViewById(R.id.grid_view);
        taskList();

        rootView.findViewById(R.id.tv_all).setOnClickListener(this);
        recyclerView = rootView.findViewById(R.id.recycler_view);
        linearLayoutCompat = rootView.findViewById(R.id.ll_empty);

        tVlearnTime = rootView.findViewById(R.id.tv_learningTime);
        tVcourseCount = rootView.findViewById(R.id.tv_courseCount);
        tVtrainingCount = rootView.findViewById(R.id.tv_trainingCount);
        tVexamCount = rootView.findViewById(R.id.tv_examCount);

        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mTaskAdapter = new TaskAdapter(R.layout.item_grid_task);
        mTaskAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(mTaskAdapter);
        int divider = DisplayUtil.dip2px(5f);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getAdapter() == null) return;
                if (parent.getChildAdapterPosition(view) % 2 == 0) {
                    outRect.set(0, 0, divider, divider);
                } else {
                    outRect.set(divider, 0, 0, divider);
                }
            }
        });


    }
    private void tryToSwitch() {
        SharedPreferences settings = getActivity().getSharedPreferences("tryToSwitch", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("tryToSwitch", 1);//默认1
        editor.commit();
        addDisposable(RetrofitService.getNetService()
                .getTryToSwitch( 2)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        //Use 0 or MODE_PRIVATE for the default operation
                        editor.putInt("tryToSwitch", response.getData()); //1  H5  2 原生
                        editor.commit();
                    }else {
                        showBindToast(response.getErrorInfo());
                    }
                }, Throwable::printStackTrace));
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getTaskData();
        getStudyData();
    }

    private void taskList() {
        gridView.setLayoutManager(new GridLayoutManager(getContext(), 5) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        BaseQuickAdapter<Function, BaseViewBindingHolder<ItemFunctionBinding>> adapter =
                new BaseQuickAdapter<Function, BaseViewBindingHolder<ItemFunctionBinding>>(R.layout.item_function) {
                    @Override
                    protected void convert(@NotNull BaseViewBindingHolder<ItemFunctionBinding> holder, Function function) {
                        ItemFunctionBinding binding = holder.getViewBinding();
                        binding.tvFunction.setText(function.name);
                        binding.tvFunction.setCompoundDrawablesRelativeWithIntrinsicBounds(
                                0, function.drawableId, 0, 0);
                    }

                    @NotNull
                    @Override
                    protected BaseViewBindingHolder<ItemFunctionBinding> onCreateDefViewHolder(
                            @NotNull ViewGroup parent, int viewType) {
                        ItemFunctionBinding binding = ItemFunctionBinding.inflate(
                                getLayoutInflater(), parent, false);
                        return new BaseViewBindingHolder<>(binding);
                    }
                };
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (ClickCheck.isFastClick()) return;
            mHasClickToNewPage = true;
            switch (position) {
                case 0:// 我的任务
                    TaskListActivity.actionStart(getContext());
                    break;
                case 1:// 我的课程
                    startActivity(new Intent(getActivity(), MyCourseActivity.class));
                    break;
                case 2:// 我的练习
                    startActivity(new Intent(getActivity(), AnswerExercisesActivity.class));
                    break;
                case 4:// 我的测评
                case 5:// 我的报名
                    showBindToast("该功能暂未开放");
                    break;
                case 3:// 我的考试
                    ExaminationListActivity.actionStart(getContext());
                    break;
                case 6:// 我的培训
                    startActivity(new Intent(getActivity(), MyTrainActivity.class));
                    break;
            }
        });
        gridView.setAdapter(adapter);
        List<Function> functionList = new ArrayList<>();
        functionList.add(new Function("我的任务", R.mipmap.task, null));
        functionList.add(new Function("我的课程", R.mipmap.cource, null));
        functionList.add(new Function("我的练习", R.mipmap.exercise, null));
        functionList.add(new Function("我的考试", R.mipmap.exam, null));
        functionList.add(new Function("我的测评", R.mipmap.appraisal, null));
        functionList.add(new Function("我的报名", R.mipmap.apply, null));
        functionList.add(new Function("我的培训", R.mipmap.grade, null));
        adapter.setList(functionList);
    }

    private void getTaskData() {
        addDisposable(RetrofitService.getNetService()
                .getTaskList(1, 2, 1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (response.getData().getList().size() == 0){
                            linearLayoutCompat.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.GONE);
                        }else if (response.getData().getList().size()>0) {
                            mTaskAdapter.setList(response.getData().getList());
                            linearLayoutCompat.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                        }
                    }else {
                        showBindToast(response.getErrorInfo());
                    }
                }, Throwable::printStackTrace));
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        TaskListBean taskListBean = mTaskAdapter.getItem(position);
        if (taskListBean.getTaskType() == 1) {// 课程
            Curriculum curriculum = new Curriculum();
            curriculum.setId(taskListBean.getBusinessId());
            curriculum.setSnapshotId(taskListBean.getBusinessId() + "");
            curriculum.setName(taskListBean.getName());
            curriculum.setCoverImage(taskListBean.getCoverImage());
            curriculum.setCourseUserId(taskListBean.getCourseUserId());
            CurriculumDetailsActivity.actionStart(getContext(), curriculum, CurriculumDetailsActivity.TYPE_FROM_TASK);
        } else if (taskListBean.getTaskType() == 2) {// 考试
            try {
                String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                String url = WebViewHelper.getBaseUrl() + "exam/examInfo?sourceId=" + taskListBean.getBusinessId() + "&fromType=1&token=" + token;
                Log.e("MyWebViewActivity", "url: " + url);

//                MyWebViewActivity.actionStart(getContext(), url, "", 1);

                SharedPreferences settingss = getActivity().getSharedPreferences("tryToSwitch", 0);
                int isAmazing = settingss.getInt("tryToSwitch", 0);

                if (isAmazing == 2) {
                    //梁尔宾 原生去考试
                    Intent intent = new Intent(getActivity(), TheTestActivity.class);
                    intent.putExtra("examId", taskListBean.getBusinessId()+ "");
                    intent.putExtra("relationshipId", "");
                    startActivity(intent);
                } else {
                    MyWebViewActivity.actionStart(view.getContext(), url, "", 1);
                }



            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    private void getStudyData(){
        if(BaseApplication.getContext().getDataLogin()==null){
            return;
        }
        addDisposable(RetrofitService.getNetService()
                .getStudyData(BaseApplication.getContext().getDataLogin().getToken())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (response.getData().getLearnTime()>0)
                        tVlearnTime.setText(formatDateTime(response.getData().getLearnTime()));
                        tVexamCount.setText(response.getData().getExamCount()+"");
                        tVtrainingCount.setText(response.getData().getTrainingCount()+"");
                        tVcourseCount.setText(response.getData().getCourseCount()+"");
                    }else {
                        showBindToast(response.getErrorInfo());
                    }
                },
                        throwable -> {
                            Tips.RequestError(getActivity());
                            throwable.printStackTrace();
                        }));
    }


        public static String formatDateTime(long mss) {
            String DateTimes = null;
            long days = mss / ( 60 * 60 * 24);
            long hours = (mss  / (60 * 60));
            long minutes = (mss % ( 60 * 60)) /60;
            long seconds = mss % 60;
             if(hours>0){
                DateTimes=hours + "小时" + minutes + "分钟";
            }else if(minutes>0){
                DateTimes=minutes + "分钟";
            }else{
                DateTimes="0分钟";
            }

            return DateTimes;
        }

    private static class TaskAdapter extends BaseQuickAdapter<TaskListBean, BaseViewHolder> {

        TaskAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, TaskListBean task) {
            ImageView imageView = baseViewHolder.getView(R.id.iv_icon);
            if (CompatHelper.isEmpty(task.getCoverImage()) && task.getTaskType() == 2) {// 考试类别，没有图片
                imageView.setImageResource(R.drawable.ic_default_list_task);
            } else {
                ImageLoaderKt.loadImage(imageView, task.getCoverImage());
            }
            baseViewHolder.setText(R.id.tv_title, task.getName().trim())
                    .setText(R.id.tv_limit_time, new StringBuilder("截止：")
                            .append(CompatHelper.isEmpty(task.getEndTime()) ? "--" : CompatHelper.getDateString(task.getEndTime())))
                    .setText(R.id.tv_task_type, new StringBuilder("任务类型：").append(task.getTaskType() == 1 ? "课程" : "考试"));
        }
    }
}
